import React, { useState, useEffect, forwardRef } from 'react';
import { 
  Box, 
  Typography, 
  Grid, 
  CircularProgress, 
  Card, 
  CardContent,
  Divider,
  Chip,
  Alert,
  Button,
  List,
  ListItem,
  ListItemText,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  IconButton,
  Slide,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Paper
} from '@mui/material';
import KeyboardArrowLeftIcon from '@mui/icons-material/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import CloseIcon from '@mui/icons-material/Close';
import { useAuth } from 'contexts/AuthContext';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Customer, Plans } from 'api/queries';
import { CancelSubscription, CreateCustomerPortalSession } from 'api/mutations';
import { useTranslation } from 'react-i18next';
//import { SubscriptionButton } from 'components/atoms/ReusableButton';
import { formatMoney } from 'libs/utils';
import { ENABLE_CUSTOMER_PORTAL } from 'config';
import moment from 'moment';

/**
 * SubscriptionUserInterface - Unified component for subscription management
 * 
 * This component can:
 * 1. Display subscription details
 * 2. Cancel subscription
 * 3. Manage plans
 * 
 * @param {Object} props
 * @param {string} props.subscriptionId - Optional subscription ID for specific subscription actions
 * @param {string} props.actionType - Optional action type: 'view', 'cancel'
 * @param {string} props.title - Optional custom title
 * @param {string} props.description - Optional custom description
 * @param {boolean} props.showPaymentMethods - Whether to show payment methods section
 * @param {boolean} props.initiallyExpanded - Whether to show the UI initially or just the button
 * @param {string} props.buttonText - Optional custom button text to override translation
 * @param {boolean} props.simpleButton - If true, renders just the button without any wrappers (default: false)
 * 
 * @example
 * // Basic usage - shows button that reveals subscription details
 * <SubscriptionUserInterface />
 * 
 * @example
 * // Cancel subscription interface
 * <SubscriptionUserInterface 
 *   subscriptionId="sub_123456"
 *   actionType="cancel"
 *   initiallyExpanded={false}
 * />
 * 
 * @example
 * // Simple button with custom text
 * <SubscriptionUserInterface
 *   buttonText="Manage Subscription"
 *   simpleButton={true}
 * />
 */
const SubscriptionUserInterface = ({ 
  subscriptionId,
  actionType = 'view',
  title,
  description,
  showPaymentMethods = true,
  initiallyExpanded = false,
  buttonText,
  simpleButton = false
}) => {
  const { user } = useAuth();
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState(initiallyExpanded);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [actionState, setActionState] = useState(null);
  const [subscriptions, setSubscriptions] = useState([]);
  const [activeSubscriptionIndex, setActiveSubscriptionIndex] = useState(0);
  const [selectedPlan, setSelectedPlan] = useState(null);
  const [isSuccess, setIsSuccess] = useState(false);
  const [error, setError] = useState(null);
  
  // Transition component for Dialog
  const DialogTransition = forwardRef(function Transition(props, ref) {
    return <Slide direction="up" ref={ref} {...props} />;
  });

  // Mutations
  const cancelSubscriptionMutation = useMutation(CancelSubscription, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Customer"]);
      setIsSuccess(true);
      setConfirmDialogOpen(false);
      if (isSuccess) {
        console.log(isSuccess);
      }
      // Show success message
      setActionState({
        success: true,
        result: { message: t("subscription.cancelSuccess") }
      });
      
      // Automatically reload data after short delay
      setTimeout(() => {
        customerQuery.refetch();
      }, 2000);
    },
    onError: (err) => {
      setError(err.message || t("common.errorOccurred"));
      setActionState({
        error: { message: err.message || t("common.errorOccurred") }
      });
    }
  });

  const customerPortalMutation = useMutation(CreateCustomerPortalSession, {});

  // Handle customer portal
  const handleCustomerPortal = async () => {
    try {
      const response = await customerPortalMutation.mutateAsync();
      window.location.href = response.data.redirect_url;
      return { message: t("subscription.redirectingToPortal") };
    } catch (err) {
      setError(err.message || t("common.errorOccurred"));
      return { error: err };
    }
  };

  // Queries
  const customerQuery = useQuery(
    ["Customer", user?.accountId],
    Customer,
    { 
      retry: false,
      enabled: !!user?.accountId && dialogOpen,
      onSuccess: (data) => {
        const allSubscriptions = data.data.subscriptions.data || [];
        setSubscriptions(allSubscriptions);
        
        // Set active subscription index based on subscriptionId (if provided)
        if (subscriptionId) {
          const index = allSubscriptions.findIndex(s => s.id === subscriptionId);
          if (index !== -1) {
            setActiveSubscriptionIndex(index);
            
            // Open cancel dialog if action is 'cancel'
            if (actionType === 'cancel') {
              setConfirmDialogOpen(true);
            }
          }
        }
      }
    }
  );

  const plansQuery = useQuery("Plans", Plans, {
    retry: false,
    enabled: dialogOpen,
    onSuccess: (data) => {
      updateSelectedPlan();
    }
  });
  
  // Update selected plan when subscription or plans data changes
  // eslint-disable-next-line
  const updateSelectedPlan = () => {
    const subscription = getCurrentSubscription();
    if (subscription && plansQuery.data?.data?.plans) {
      const plan = plansQuery.data.data.plans.find(p => p.id === subscription.plan.id);
      setSelectedPlan(plan || null);
    }
  };
  
  // Update selected plan when activeSubscriptionIndex changes
  useEffect(() => {
    updateSelectedPlan();
  }, [activeSubscriptionIndex, subscriptions, plansQuery.data, updateSelectedPlan]);

  // Format date from Unix timestamp
  const formatDate = (unixTimestamp) => {
    if (!unixTimestamp) return '';
    return moment.unix(unixTimestamp).format("DD/MM/YYYY");
  };

  // Handler for action state changes
  // eslint-disable-next-line  
  const handleActionStateChange = (state) => {
    setActionState(state);
    
    // Close confirm dialog on success
    if (state.success) {
      setConfirmDialogOpen(false);
    }
    
    // Automatically reset state after 3 seconds
    setTimeout(() => {
      setActionState(null);
    }, 3000);
  };

  // Handle the cancel action
  const handleCancelAction = () => {
    const subscription = getCurrentSubscription();
    if (!subscription) return;
    
    if (ENABLE_CUSTOMER_PORTAL) {
      handleCustomerPortal();
    } else {
      cancelSubscriptionMutation.mutate({ subscriptionId: subscription.id });
    }
  };

  // Open main dialog
  const openDialog = () => {
    setDialogOpen(true);
    return { message: t("common.loadingSubscriptionDetails") };
  };

  // Close main dialog
  const closeDialog = () => {
    setDialogOpen(false);
    setActionState(null);
  };
  
  // Open confirm dialog for cancellation
  const openConfirmDialog = () => {
    setConfirmDialogOpen(true);
  };
  
  // Close confirm dialog
  const closeConfirmDialog = () => {
    setConfirmDialogOpen(false);
    setActionState(null);
  };
  
  // Navigate to next subscription
  const nextSubscription = () => {
    setActiveSubscriptionIndex((prevIndex) => {
      return (prevIndex + 1) % subscriptions.length;
    });
  };
  
  // Navigate to previous subscription
  const prevSubscription = () => {
    setActiveSubscriptionIndex((prevIndex) => {
      return prevIndex === 0 ? subscriptions.length - 1 : prevIndex - 1;
    });
  };
  
  // Get current active subscription
  const getCurrentSubscription = () => {
    if (!subscriptions.length || activeSubscriptionIndex >= subscriptions.length) return null;
    return subscriptions[activeSubscriptionIndex];
  };

  // Loading state
  const isLoading = customerQuery.isLoading || plansQuery.isLoading || 
                   cancelSubscriptionMutation.isLoading || customerPortalMutation.isLoading;
  
  // Check for errors
  const hasError = customerQuery.isError || plansQuery.isError || !!error;

  // If not expanded, just show the button
  if (!dialogOpen) {
    const buttonProps = {
      view: {
        title: title || t("subscription.pageTitle"),
        description: description || t("subscription.pageDescription"),
        buttonText: buttonText || t("subscription.viewSubscription")
      },
      cancel: {
        title: title || t("subscription.cancelSubscription"),
        description: description || t("subscription.cancelSubscriptionDescription"),
        buttonText: buttonText || t("subscription.showCancellationOptions")
      }
    };

    const currentProps = buttonProps[actionType] || buttonProps.view;

    // If simpleButton is true, render just the button without wrappers
    if (simpleButton) {
      return (
        <Button
          variant="contained"
          color="primary"
          size="large"
          onClick={openDialog}
        >
          {currentProps.buttonText}
        </Button>
      );
    }

    return (
      <Box textAlign="center" py={4}>
        <Typography variant="h5" component="h2" gutterBottom>
          {currentProps.title}
        </Typography>
        
        {currentProps.description && (
          <Typography paragraph>
            {currentProps.description}
          </Typography>
        )}
        
        <Box mt={3}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={openDialog}
          >
            {currentProps.buttonText}
          </Button>
        </Box>
      </Box>
    );
  }
  
  // Render cancel confirmation dialog
  const renderCancelDialog = () => {
    const subscription = getCurrentSubscription();
    if (!subscription) return null;
    
    // If subscription is already canceled
    if (subscription.canceled_at) {
      return (
        <Dialog 
          open={confirmDialogOpen} 
          onClose={closeConfirmDialog}
          fullWidth
          maxWidth="sm"
          TransitionComponent={DialogTransition}
        >
          <DialogTitle>
            {t("subscription.cancelSubscription")}
            <IconButton
              aria-label="close"
              onClick={closeConfirmDialog}
              sx={{
                position: 'absolute',
                right: 8,
                top: 8,
              }}
            >
              <CloseIcon />
            </IconButton>
          </DialogTitle>
          <DialogContent>
            <Alert severity="info" sx={{ mb: 2 }}>
              {t("subscription.alreadyCanceled")}
            </Alert>
            
            <Typography>
              {t("subscription.willDeactivateOn")}: {formatDate(subscription.current_period_end)}
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={closeConfirmDialog}>
              {t("common.close")}
            </Button>
          </DialogActions>
        </Dialog>
      );
    }
    
    return (
      <Dialog 
        open={confirmDialogOpen} 
        onClose={closeConfirmDialog}
        fullWidth
        maxWidth="md"
        TransitionComponent={DialogTransition}
      >
        <DialogTitle>
          {t("subscription.cancelSubscription")}
          <IconButton
            aria-label="close"
            onClick={closeConfirmDialog}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 3 }}>
            {t("subscription.cancelWarning")}
          </Alert>
          
          <Card variant="outlined" sx={{ mb: 3 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                {selectedPlan?.title || t("subscription.unknownPlan")}
              </Typography>
              
              <Divider sx={{ my: 2 }} />
              
              <TableContainer component={Paper} variant="outlined">
                <Table size="small">
                  <TableBody>
                    <TableRow>
                      <TableCell component="th" scope="row" sx={{ width: '50%' }}>
                        {t("subscription.price")}
                      </TableCell>
                      <TableCell>
                        {selectedPlan?.price !== undefined && selectedPlan?.currency ? 
                          formatMoney("it", selectedPlan.currency, selectedPlan.price) : 
                          "—"
                        }
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell component="th" scope="row">
                        {t("subscription.currentPeriodEnd")}
                      </TableCell>
                      <TableCell>
                        {formatDate(subscription.current_period_end)}
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
          
          <Typography variant="h6" gutterBottom>
            {t("subscription.whatHappensAfterCancel")}:
          </Typography>
          
          <List>
            <ListItem>
              <ListItemText primary={t("subscription.accessUntilEndOfBillingPeriod")} />
            </ListItem>
            <ListItem>
              <ListItemText primary={t("subscription.noMoreCharges")} />
            </ListItem>
            <ListItem>
              <ListItemText primary={t("subscription.canResubscribeAnytime")} />
            </ListItem>
          </List>
          
          {actionState && actionState.error && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {actionState.error.message || t("common.actionFailed")}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={closeConfirmDialog}>
            {t("subscription.keepSubscription")}
          </Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleCancelAction}
            disabled={cancelSubscriptionMutation.isLoading}
          >
            {cancelSubscriptionMutation.isLoading ? 
              t("common.processing") : 
              t("subscription.confirmCancel")
            }
          </Button>
        </DialogActions>
      </Dialog>
    );
  };
  
  // Render subscription content with CSS-based sliding transitions
  const renderSubscriptionContent = () => {
    if (!subscriptions.length) return null;
    
    return (
      <Box sx={{ 
        position: 'relative', 
        overflow: 'hidden', 
        height: '320px',  // Fixed height to prevent jumping
        mb: 2
      }}>
        {subscriptions.map((subscription, index) => {
          const planForSub = plansQuery.data?.data?.plans?.find(p => p.id === subscription.plan.id);
          
          return (
            <Box
              key={subscription.id}
              sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                transition: 'transform 300ms ease, opacity 300ms ease',
                transform: `translateX(${(index - activeSubscriptionIndex) * 100}%)`,
                opacity: index === activeSubscriptionIndex ? 1 : 0,
                visibility: Math.abs(index - activeSubscriptionIndex) <= 1 ? 'visible' : 'hidden', // Only render nearby subscriptions
                zIndex: index === activeSubscriptionIndex ? 2 : 1,
              }}
            >
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    {planForSub?.title || t("subscription.unknownPlan")}
                  </Typography>
                  
                  <Box display="flex" justifyContent="flex-start" alignItems="center" mb={1}>
                    <Chip 
                      label={subscription.canceled_at ? t("subscription.canceled") : t("subscription.active")}
                      color={subscription.canceled_at ? "error" : "success"}
                      size="small"
                    />
                  </Box>
                  
                  <TableContainer sx={{ mb: 2 }}>
                    <Table size="small">
                      <TableBody>
                        <TableRow>
                          <TableCell component="th" scope="row" sx={{ width: '40%' }}>
                            {t("subscription.price")}
                          </TableCell>
                          <TableCell>
                            {planForSub?.price !== undefined && planForSub?.currency ? 
                              formatMoney("it", planForSub.currency, planForSub.price) : 
                              "—"
                            }
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell component="th" scope="row">
                            {subscription.canceled_at 
                              ? t("subscription.willDeactivateOn")
                              : t("subscription.renewsOn")}
                          </TableCell>
                          <TableCell>
                            {formatDate(subscription.current_period_end)}
                          </TableCell>
                        </TableRow>
                        <TableRow>
                          <TableCell component="th" scope="row">
                            {t("subscription.id")}
                          </TableCell>
                          <TableCell sx={{ fontFamily: 'monospace', fontSize: '0.8rem', wordBreak: 'break-all' }}>
                            {subscription.id}
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    </Table>
                  </TableContainer>
                  
                  <Divider sx={{ my: 1 }} />
                  
                  <Grid container spacing={1} sx={{ mt: 1 }}>
                    {!subscription.canceled_at && (
                      <Grid item xs={12} sm={6}>
                        <Button
                          variant="outlined"
                          color="error"
                          size="small"
                          fullWidth
                          onClick={openConfirmDialog}
                        >
                          {t("subscription.cancelSubscription")}
                        </Button>
                      </Grid>
                    )}
                    
                    {ENABLE_CUSTOMER_PORTAL && (
                      <Grid item xs={subscription.canceled_at ? 12 : 6} sm={6}>
                        <Button
                          variant="outlined"
                          size="small"
                          fullWidth
                          onClick={handleCustomerPortal}
                        >
                          {t("subscription.manageBilling")}
                        </Button>
                      </Grid>
                    )}
                  </Grid>
                </CardContent>
              </Card>
            </Box>
          );
        })}
      </Box>
    );
  };

  // Main dialog content
  const renderMainDialog = () => {
    // Render loading state
    if (isLoading) {
      return (
        <Box display="flex" justifyContent="center" alignItems="center" p={4}>
          <CircularProgress />
        </Box>
      );
    }
    
    // Render error state
    if (hasError) {
      return (
        <Alert severity="error" sx={{ m: 2 }}>
          {error || t("common.errorLoadingData")}
        </Alert>
      );
    }
    
    // No subscriptions found
    if (!subscriptions.length) {
      return (
        <Box textAlign="center" p={3}>
          <Alert severity="warning" sx={{ mb: 3 }}>
            {t("subscription.noActiveSubscription")}
          </Alert>
          
          <Button 
            variant="contained"
            color="primary"
            onClick={() => window.location.href = '/plan'}
          >
            {t("subscription.selectPlan")}
          </Button>
        </Box>
      );
    }
    
    // Has subscriptions
    return (
      <>
        {/* Navigation controls */}
        {subscriptions.length > 1 && (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', mb: 2 }}>
            <IconButton onClick={prevSubscription} size="small" aria-label="Previous subscription">
              <KeyboardArrowLeftIcon />
            </IconButton>
            
            <Typography variant="body2" sx={{ mx: 2 }}>
              {t("subscription.count", { current: activeSubscriptionIndex + 1, total: subscriptions.length })}
            </Typography>
            
            <IconButton onClick={nextSubscription} size="small" aria-label="Next subscription">
              <KeyboardArrowRightIcon />
            </IconButton>
          </Box>
        )}
        
        {actionState && actionState.success && (
          <Alert severity="success" sx={{ mb: 2 }}>
            {actionState.result?.message || t("common.actionSuccessful")}
          </Alert>
        )}
        
        {actionState && actionState.error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {actionState.error.message || t("common.actionFailed")}
          </Alert>
        )}
        
        {/* Sliding subscription cards */}
        {renderSubscriptionContent()}
        
        {/* Additional actions */}
        <Box sx={{ mt: 3 }}>
          <Typography variant="subtitle2" gutterBottom>
            {t("subscription.additionalActions")}
          </Typography>
          
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <Button
                variant="outlined"
                fullWidth
                onClick={() => window.location.href = '/plan'}
              >
                {t("subscription.changePlan")}
              </Button>
            </Grid>
            
            {showPaymentMethods && (
              <Grid item xs={12} sm={6}>
                <Button
                  variant="outlined"
                  fullWidth
                  onClick={() => window.location.href = '/payment-methods'}
                >
                  {t("paymentMethods.viewPaymentMethods")}
                </Button>
              </Grid>
            )}
            
            <Grid item xs={12}>
              <Button
                variant="outlined"
                fullWidth
                onClick={() => window.location.href = '/payment-history'}
              >
                {t("paymentHistory.viewPaymentHistory")}
              </Button>
            </Grid>
          </Grid>
        </Box>
      </>
    );
  };

  return (
    <>
      {/* Initial button to open dialog */}
      {!dialogOpen && (
        // This section is only rendered if simpleButton is false (handled above)
        <Box textAlign="center" py={4}>
          <Typography variant="h5" component="h2" gutterBottom>
            {title || (actionType === 'cancel' 
              ? t("subscription.cancelSubscription") 
              : t("subscription.pageTitle"))}
          </Typography>
          
          {description && (
            <Typography paragraph>
              {description}
            </Typography>
          )}
          
          <Box mt={3}>
            <Button
              variant="contained"
              color="primary"
              size="large"
              onClick={openDialog}
            >
              {buttonText || (actionType === 'cancel' 
                ? t("subscription.showCancellationOptions") 
                : t("subscription.viewSubscription"))}
            </Button>
          </Box>
        </Box>
      )}
      
      {/* Main Dialog with Subscription */}
      <Dialog
        open={dialogOpen}
        onClose={closeDialog}
        fullWidth
        maxWidth="md"
        TransitionComponent={DialogTransition}
      >
        <DialogTitle>
          {title || t("subscription.pageTitle")}
          <IconButton
            aria-label="close"
            onClick={closeDialog}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent>
          {renderMainDialog()}
        </DialogContent>
        <DialogActions>
          <Button onClick={closeDialog}>
            {t("common.close")}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Cancellation Confirmation Dialog */}
      {renderCancelDialog()}
    </>
  );
};

export default SubscriptionUserInterface;